/**
 * 
 */
package com.gr.staffpm.tasks.model;

import org.apache.shiro.SecurityUtils;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.gr.staffpm.datatypes.Task;
import com.gr.staffpm.pages.tasks.ViewTask;
import com.gr.staffpm.security.constants.StaffPMRoles;
import com.gr.staffpm.security.service.UserService;


/**
 * @author Graham Rhodes 16 Jan 2011 16:52:09
 */
public class TaskLink extends Link<Task> {

    private final UserService userService;

    /**
     * @param id
     * @param model
     * @see org.apache.wicket.Component#Component(String, IModel)
     */
    public TaskLink(final String id, IModel<Task> model, UserService userService) {
        super(id, model);
        this.userService = userService;
    }

    /**
     * @param id
     * @param project
     */
    public TaskLink(String id, Task task, UserService userService) {
        super(id, new Model<Task>(task));
        this.userService = userService;
    }

    private static final long serialVersionUID = 1L;

    @Override
    public void onClick() {
        Task t = getModelObject();
        boolean owner = userService.getCurrentUser().equals(t.getAssignee()) || userService.getCurrentUser().equals(t.getCreatedBy());
        boolean admin = SecurityUtils.getSubject().hasRole(StaffPMRoles.ADMIN);

        if (SecurityUtils.getSubject().isPermitted("task:read:" + t.getTaskId())
                || admin
                || owner
                || SecurityUtils.getSubject().isPermitted("project:readtasks:" + t.getProject().getProjectId())) {
            setResponsePage(new ViewTask(new PageParameters("id=" + String.valueOf(t.getTaskId()))));
        } else
            error("You do not have permission to read task: " + t.getName());
    }
}
